from myblog.models import MamahaoTestRequestTestCase, MamahaoResponseContentReport, MamahaoTestPublicInterface, \
    MamahaoTestHeards,MamahaoResponseReportResult
import requests
from myblog.mamahaoService.mamahaoJOBService.mamahaoProcessingData import ModelData
from myblog.mamahaoService.mamahaoJOBService.mamahaoProvideMethod import method
from myblog.mamahaoService.mamahaoJOBService.mamhaoJsondict import jsondict
from myblog.mamahaoJOB import configHttp
import logging

logger = logging.getLogger('log')


class ExecutionCase(object):
    def singleeExecution(self, caseList):
        """
        执行数据
        :param caseList:
        :return:
        """
        try:
            for i in range(len(caseList)):
                case = MamahaoTestRequestTestCase.objects.filter(case_id=caseList[i])
                if case == None: continue
                data = ModelData().dataBaseHandle(case.values()[0])  # 获取数据库中的data
                dictlsitall = method().JOBcheckCaseAll(data)  # 执行数据case，获得最后Case的结果
                sqldata = {
                    "sqlTrueFlasetypeLast": data["sqlTrueFlasetypeLast"],
                    "id": data["sqlChoiceLast"],
                    "sql": data["SQLinputLast"],
                    "SQLMomentum": data["SQLMomentumLast"],
                    "sqlClusionValueLast": data["sqlClusionValueLast"],
                }
                rustl = method().AssertionResults(request_result=data["request_result"], result=dictlsitall["data"],
                                                  reusltlist=dictlsitall["reuslt"], sqldata=sqldata)

                myCase = MamahaoTestRequestTestCase.objects.get(case_id=caseList[i])
                myCase.request_response = rustl["AssertionLsit"]
                myCase.request_code = rustl["Assertion"]
                myCase.request_result_Assertion_content = dictlsitall["data"]
                myCase.save()
            return None
        except EOFError as e:
            logger.error(e)

    def singleeExecutionMore(self, caseList, id):
        """
        异步任务执行
        :param caseList:
        :param id:
        :return:
        """
        try:
            Success = 0
            Fail = 0
            Skip = 0
            for i in range(len(caseList)):
                case = MamahaoTestRequestTestCase.objects.filter(case_id=caseList[i])
                if case == None: continue
                data = ModelData().dataBaseHandle(case.values()[0])  # 获取数据库中的data
                dictlsitall = method().JOBcheckCaseAll(data)  # 执行数据case，获得最后Case的结果
                sqldata = {
                    "sqlTrueFlasetypeLast": data["sqlTrueFlasetypeLast"],
                    "id": data["sqlChoiceLast"],
                    "sql": data["SQLinputLast"],
                    "SQLMomentum": data["SQLMomentumLast"],
                    "sqlClusionValueLast": data["sqlClusionValueLast"],
                }
                rustl = method().AssertionResults(request_result=data["request_result"], result=dictlsitall["data"],
                                                  reusltlist=dictlsitall["reuslt"], sqldata=sqldata)

                myCase = MamahaoTestRequestTestCase.objects.get(case_id=caseList[i])
                myCase.request_response = rustl["AssertionLsit"]
                myCase.request_code = rustl["Assertion"]
                myCase.request_result_Assertion_content = dictlsitall["data"]
                myCase.save()
                k = i + 1
                speedOfProgress = int((k / len(caseList)) * 1000) / 1000
                if k == len(caseList): speedOfProgress = 1
                execution_progress = str(speedOfProgress * 100) + "%"
                cr = MamahaoResponseContentReport.objects.get(plan_id=id)
                cr.execution_progress = execution_progress
                cr.save()
                caseSuccess = str(myCase.request_code)
                if caseSuccess == "success": Success = Success + 1
                if caseSuccess == "skip": Skip = Skip + 1
                if caseSuccess == "fail": Fail = Fail + 1
                print("执行结果：", caseSuccess)
            mcr = MamahaoResponseContentReport.objects.get(plan_id=id)
            mcr.successs_case = Success
            mcr.fail_case = Fail
            mcr.skip_case = Skip
            mcr.save()
            mrrr=MamahaoResponseReportResult(plan_id=mcr.plan_id,plan_name=mcr.plan_name,successs_case=mcr.successs_case,
                                             fail_case=mcr.fail_case,skip_case=mcr.skip_case,case_total=mcr.case_total,
                                             timing_open_close=mcr.timing_open_close)

            mrrr.save()
            return None
        except EOFError as e:
            logger.error(e)

    def runRepositoryPublicMethod(self, id):
        """
        运行公共方法并存库
        :param id:
        :return:
        """

        mmhPI = MamahaoTestPublicInterface.objects.get(request_id=id)
        url = mmhPI.url
        method = mmhPI.method
        request_data_type = mmhPI.request_data_type
        request_header_param = mmhPI.request_header_param
        if request_header_param == "":
            request_header_param = {}
        else:
            request_header_param = eval(request_header_param)
        request_data_content = mmhPI.request_data_content
        request_value = eval(mmhPI.request_value)
        methodname = str(request_data_type) + str(method)
        self.url = url
        self.headers = request_header_param
        self.params = eval(request_data_content)
        self.data = eval(request_data_content)
        self.cookies = {}
        if methodname == "DATAGET": Result = configHttp.ConfigHttp.dataget(self)
        if methodname == "DATAPOST": Result = configHttp.ConfigHttp.datapost(self)
        if methodname == "JSONGET": Result = configHttp.ConfigHttp.jsonget(self)
        if methodname == "JSONPOST": Result = configHttp.ConfigHttp.jsonpost(self)
        valuesList = {}
        for i in range(len(request_value)):
            keyName = request_value[i]["newKey"]
            realkeyNme = request_value[i]["realkey"]
            num = request_value[i]["newValue"]

            if num == "":
                value = jsondict().get_target_value(keyName, Result.json(), [])
            else:
                value = jsondict().get_target_value(keyName, Result.json(), [])[num]

            valuesList[realkeyNme] = str(value)

        mmhHerd = MamahaoTestHeards.objects.get(tpi_id=id)
        mmhHerd.headrsValues = valuesList
        mmhHerd.save()
        logger.info("--更新完成当前头部信息---%s" % mmhHerd.headrsName)
        return valuesList
